<?php
/**
 * 使用Authorization Code换取Access Token
 *
 * 默认情况下，Access Token的有效期为1天。
 *
 * 应用需要在接收Authorization Code 的服务端程序中发送请求（推荐post）到授权服务器“https://graph.renren.com/oauth/token”，并带上5个必须参数。
 * grant_type：使用Authorization Code 作为Access Grant时，此值为“authorization_code”。 
 * code：Authorization Code； 
 * client_id：应用的API Key； 
 * client_secret：应用的Secret Key； 
 * redirect_uri：必须与获取Authorization Code时传递的“redirect_uri”保持一致。
 */
@header('Pragma:no-cache');
@header('Cache-Control:no-cache');
$code = empty($_GET['code']) ? null : $_GET['code'];
if(null !== $code) {
	$grant_type = 'authorization_code';
	$client_id = '9bbac42e58c844cd85c89aa7529c6f00';
	$client_secret = '7e099f5ebb8346c18453fd2539f47555';
	$redirect_uri = 'http://www.example.com/framework/Renren/doc/authorize/callback.php';
	//$url = "https://graph.renren.com/oauth/token?client_id={$client_id}&client_secret={$client_secret}&redirect_uri={$redirect_uri}&grant_type={$grant_type}&code={$code}";
	$url = "https://graph.renren.com/oauth/token?redirect_uri={$redirect_uri}&grant_type={$grant_type}&code={$code}";
	$params = array(
		'client_id' => $client_id,
		'client_secret' => $client_secret,
	);
	$ret = http($url, 'POST', $params);
	$ret = json_decode($ret, true);
	var_dump($ret);
	$access_token = $ret['access_token'];
}

function http($url, $method, $postfields = array(), $multi = false){
	$urlArr = parse_url($url);
	//check https
	$version = '1.1';
	$host = $header_host = isset($urlArr['host']) ? $urlArr['host'] : '';
	if('https' === strtolower($urlArr['scheme'])) {
		$port = (isset($urlArr['port']) && '443' !== $urlArr['port']) ? $urlArr['port'] : '443';
		$host = "ssl://{$host}";
	} else {
		$port = (isset($urlArr['port']) && '80' !== $urlArr['port']) ? $urlArr['port'] : '80';
	}
	
	$requestPath = $urlArr['path'];
	if(isset($urlArr['query'])) $requestPath .= "?{$urlArr['query']}";

	$header = "{$method} {$requestPath} HTTP/{$version}\r\n";
	$header .= "Host: {$header_host}\r\n";
	if('post' === strtolower($method)) {
		//handle $postfields
		$postfieldsStr = '';
		if($multi) {
			$boundary = "---------------------------".substr(md5(rand(0,32000)),0,10);
			$header .= "Content-Type: multipart/form-data; boundary={$boundary}\r\n";
			foreach($postfields as $key => $val) {
				$postfieldsStr .= "--{$boundary}\r\n";
				if(is_file($val) && file_exists($val)) {
					$postfieldsStr .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"" . basename($val) . "\"\r\n";
					$postfieldsStr .= "Content-Type: " . getMimeType($val) . "\r\n\r\n";
					$postfieldsStr .= file_get_contents($val) . "\r\n";
				} else {
					$postfieldsStr .= "Content-Disposition: form-data; name=\"{$key}\"\r\n\r\n";
					$postfieldsStr .= "{$val}\r\n";
				}
			}
			
			$postfieldsStr .= "--{$boundary}--\r\n";
		} else {
			$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
			foreach($postfields as $key => $val) {
				$postfieldsStr .= urlencode($key) . '=' . urlencode($val) . '&';
			}
			$postfieldsStr = substr($postfieldsStr, 0, -1);
		}
		
		$header .= "Content-Length: ".strlen($postfieldsStr)."\r\n";
		$header .= "Connection: Close\r\n\r\n";
		$header .= $postfieldsStr;
	} else {
		$header .= "Connection: Close\r\n\r\n";
	}

	$ret = '';
	
	$fp = fsockopen($host,$port,$errno,$errstr,30);

	if(!$fp) {
		throw new Exception('open socket fail');
	} else {
		fwrite($fp, $header);
		while(!feof($fp)) {
			$ret .= fgets($fp, 4096);
		}
		fclose($fp);
		if(false !== strrpos($ret,'Transfer-Encoding: chunked')){
			$info = explode("\r\n\r\n",$ret);
			$response = explode("\r\n",$info[1]);
			$t = array_slice($response,1,-1);

			$returnInfo = implode('',$t);
		}else{
			$response = explode("\r\n\r\n",$ret);
			$returnInfo = $response[1];
		}
		
		return $returnInfo;
	}
}

function getMimeType($filename) {
	$mime_types = array(
		'txt' => 'text/plain',
		'htm' => 'text/html',
		'html' => 'text/html',
		'php' => 'text/html',
		'css' => 'text/css',
		'js' => 'application/javascript',
		'json' => 'application/json',
		'xml' => 'application/xml',
		'swf' => 'application/x-shockwave-flash',
		'flv' => 'video/x-flv',
		
		// images
		'png' => 'image/png',
		'jpe' => 'image/jpeg',
		'jpeg' => 'image/jpeg',
		'jpg' => 'image/jpeg',
		'gif' => 'image/gif',
		'bmp' => 'image/bmp',
		'ico' => 'image/vnd.microsoft.icon',
		'tiff' => 'image/tiff',
		'tif' => 'image/tiff',
		'svg' => 'image/svg+xml',
		'svgz' => 'image/svg+xml',
		
		// archives
		'zip' => 'application/zip',
		'rar' => 'application/x-rar-compressed',
		'exe' => 'application/x-msdownload',
		'msi' => 'application/x-msdownload',
		'cab' => 'application/vnd.ms-cab-compressed',
		
		// audio/video
		'mp3' => 'audio/mpeg',
		'qt' => 'video/quicktime',
		'mov' => 'video/quicktime',
		
		// adobe
		'pdf' => 'application/pdf',
		'psd' => 'image/vnd.adobe.photoshop',
		'ai' => 'application/postscript',
		'eps' => 'application/postscript',
		'ps' => 'application/postscript',
		
		// ms office
		'doc' => 'application/msword',
		'rtf' => 'application/rtf',
		'xls' => 'application/vnd.ms-excel',
		'ppt' => 'application/vnd.ms-powerpoint',
		
		// open office
		'odt' => 'application/vnd.oasis.opendocument.text',
		'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
	);
	
	$ext = strtolower(array_pop(explode('.',$filename)));
	if (array_key_exists($ext, $mime_types)) {
		return $mime_types[$ext];
	} elseif (function_exists('finfo_open')) {
		$finfo = finfo_open(FILEINFO_MIME);
		$mimetype = finfo_file($finfo, $filename);
		finfo_close($finfo);
		return $mimetype;
	} else {
		return 'application/octet-stream';
	}
}
?>
<a href="step3_session_key.php?access_token=<?php echo $access_token; ?>">Session Key</a>